import React from "react";
import { Form, Input, Modal, Select, Switch } from "antd";
import { openNotificationWithIcon } from "utils/comm";

const { Option } = Select;

const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

@Form.create()
class CreateForm extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.inputRef = React.createRef();
    this.textareaRef = React.createRef();

    this.state = {
      channelTypeList: [], // 渠道类型
    };
  }

  componentDidMount() {
    this.initStaticData();
  }

  initStaticData = () => {
    const { dispatch } = this.props;
    dispatch({ type: "channel/getChannelType" }).then(({ errCode, datas }) => {
      if (errCode === 0) {
        this.setState({
          channelTypeList: datas,
        });
      }
    });
  };

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch, data } = this.props;
    const { channelTypeList } = this.state;

    form.validateFields((err, values) => {
      if (err) {
        return;
      }

      let type = "channel/addChannel";
      if (data) type = "channel/editChannel";
      const record = data || {};

      if (values.channelType === record.channelName) {
        values.channelType = record.channelType;
      }

      if (values.channelType || data.channelType) {
        const channelType = values.channelType || data.channelType;
        const arr = channelTypeList.filter((item) => item.code === channelType);
        values.channelName = arr[0].name;
      }

      dispatch({ type, payload: { ...record, ...values } }).then((resp) => {
        const { errCode, errortext } = resp;
        if (errCode === 0) {
          this.handleCancel(true);
          form.resetFields();
          this.openNotificationWithIcon("success", "", errortext || "操作成功");
        } else {
          this.openNotificationWithIcon("warning", "", errortext || "操作失败");
        }
      });
    });
  };

  handleCancel = (isQuery = false) => {
    const { handleCreateVisible } = this.props;
    handleCreateVisible(false, "", isQuery);
  };

  render() {
    const { form, visible, confirmLoading, data = {}, title = "" } = this.props;
    const record = data || {};
    const { getFieldDecorator, getFieldValue } = form;
    const channelStatus = getFieldValue("channelStatus");
    const { channelTypeList } = this.state;
    return (
      <Modal
        title={title}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => this.handleCancel()}
        width="582px"
        centered
        confirmLoading={confirmLoading}
      >
        <Form>
          <Form.Item label="渠道编号" {...formItemLayout1}>
            {getFieldDecorator("channelCode", {
              initialValue: record.channelCode || "",
              rules: [
                { required: true, message: "请输入渠道编号" },
                {
                  pattern: /^[a-zA-Z_][a-zA-Z_0-9-]*$/,
                  message:
                    "支持字母、数字、下划线、中划线，须以字母或者下划线开头",
                },
              ],
            })(<Input placeholder="请输入渠道编号" maxLength={20} />)}
          </Form.Item>
          <Form.Item label="渠道名称" {...formItemLayout1}>
            {getFieldDecorator("channelType", {
              initialValue: record.channelName,
              rules: [{ required: true, message: "请选择渠道名称" }],
            })(
              <Select placeholder="请选择">
                {Array.isArray(channelTypeList) &&
                  channelTypeList.map((item = {}) => (
                    <Option key={item.code} value={item.code}>
                      {item.name}
                    </Option>
                  ))}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="渠道状态" {...formItemLayout1}>
            {getFieldDecorator("channelStatus", {
              initialValue: record.channelStatus || false,
              rules: [{ required: true, message: "" }],
            })(
              <Switch
                checked={Boolean(channelStatus)}
                // onChange={() => this.handleSwitchChange(status)}
              />,
            )}
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

export default CreateForm;
